<template>
  <div class="ms-login" p20>
    <a-form
      class="ms-login__form"
      :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }"
      @submit="onSubmit"
    >
      <div class="ms-login__form-title">用户登录</div>
      <a-form-item label="用户名" v-bind="validateInfos.username">
        <a-input v-model:value="loginForm.username" />
      </a-form-item>
      <a-form-item label="密码" v-bind="validateInfos.password">
        <a-input-password v-model:value="loginForm.password" />
      </a-form-item>
      <a-form-item label="验证码" v-bind="validateInfos.code">
        <a-row :gutter="20">
          <a-col :span="16">
            <a-input v-model:value="loginForm.code" />
          </a-col>
          <a-col :span="8">
            <img :src="codeImg" @click="handleGetCode" />
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
        <a-button type="primary" html-type="submit" block :loading="submitLoading">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, watch } from 'vue'
import useForm from '@/hooks/useForm'
import useCode from './useCode'
import { notification } from 'ant-design-vue'
import { useUserStore } from '@/store/user'
import router from '@/router'
import type { IUserLogin } from '@/types'
import { RouteRecordRaw } from 'vue-router'

const rulesRef = reactive({
  username: [
    {
      required: true,
      message: '请输入用户名'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码'
    }
  ],
  code: [
    {
      required: true,
      message: '请输入验证码'
    }
  ]
})
// const loginForm = reactive<NonNullable<IUserLogin>>(pickFormRequired(rulesRef))

const userStore = useUserStore()
const { submitForm, validateInfos, submitLoading, formModel: loginForm } = useForm<IUserLogin, RouteRecordRaw[]>(userStore.login, rulesRef)

// 验证码
const { handleGetCode, codeImg, codeUUid } = useCode()
watch(codeUUid, (value) => {
  loginForm.value.uuid = value
})

async function onSubmit () {
  try {
    await submitForm()
    notification.success({
      message: '登录成功',
      description: '欢迎回来'
    })
    // 登录后跳转首页
    router.push('/')
  } catch (e) {
    handleGetCode()
  }
}

</script>

<style lang="less" scoped>
  .ms-login {
    height: 100%;
    &__form {
      position: relative;
      top: 30vh;
      width: 500px;
      margin: 0 auto;
      padding: 30px 10px;
      box-shadow: 2px 2px 5px #333;

      &-title {
        margin-bottom: 20px;
        font-weight: bold;
        font-size: 24px;
        text-align: center;
      }
    }
  }
</style>
